import os.path

import bs4,requests,re
from fonts import headers

base_path = 'https://apifont.ibaotu.com/?font_path='
download_path = ''

def download(url):
    global download_path
    response = requests.get(url,headers=headers)
    if response.status_code == 200:
        soup = bs4.BeautifulSoup(response.content,'html.parser')
        name = soup.find_all('h1',class_='works-name')[0].get_text()+'.ttf'
        # 查找所有的<script>标签
        scripts = soup.find_all('script', type='text/javascript')
        # 定义正则表达式模式来匹配fontPath变量赋值语句
        pattern = re.compile(r'var fontPath\s*=\s*"([^"]+)"\s*;')
        # 遍历每个<script>标签的内容，寻找匹配的fontPath赋值语句
        for script in scripts:
            match = pattern.search(str(script.string))
            if match:
                font_path = match.group(1)
                download_path = '{0}{1}&&sub_string=1234567890'.format(base_path,font_path)
                break
        else:
            print("fontPath not found")
        if not os.path.exists('/Users/elyaranwar/Downloads/fonts/'):
            os.makedirs('/Users/elyaranwar/Downloads/fonts/')
        with open(r'/Users/elyaranwar/Downloads/fonts/{}'.format(name),'wb') as file:
            headers.update({'Range': 'bytes=0-'})
            res = requests.get(download_path,headers=headers)
            print(res.status_code)
            for data in res.iter_content(chunk_size=4096):
                file.write(data)
                # file.write(res.content)
            print('Download Success:{}'.format(name))
    else:
        print("Can't Open it")


if __name__=="__main__":
    download('https://ibaotu.com/font/661.html')